package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.icCard;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.icCard.GetIcCardBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.IcCardInfoExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.TruckExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.IcCardAuthExcelEn;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/icCard")
public class IcCardController {
    @Autowired
    private GetIcCardBu getIcCardBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;
    @GetMapping("/getIcCard")
    public SzResult getIcCard(@RequestParam(value = "page", required = false) String page,
                              @RequestParam(value = "pageSize", required = false) String pageSize,
                              @RequestParam(value = "startTime", required = false) String startTime,
                              @RequestParam(value = "endTime", required = false) String endTime,
                              @RequestParam(value = "icCardNo", required = false) String icCardNo,
                              @RequestParam(value = "co", required = false) String co,
                              @RequestParam(value = "supplyCo", required = false) String supplyCo,
                              @RequestParam(value = "tranCo", required = false) String tranCo,
                              @RequestParam(value = "cardinfAlias", required = false) String cardinfAlias,
                              @RequestParam(value = "truckNo", required = false) String truckNo,
                              @RequestParam(value = "cardType", required = false) String cardType,
                              @RequestParam(value = "icCardStatus", required = false) String icCardStatus,
                              HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return getIcCardBu.getIcCard(page, pageSize, token, startTime, endTime, icCardNo,cardinfAlias, co, supplyCo, tranCo, truckNo, cardType, icCardStatus, plantId);
    }


    //从user表里只获得司机的信息
    @GetMapping("/getDriverFromUser")
    public SzResult getDriverFromUser() {
        return getIcCardBu.getDriverFromUser();
    }

    @GetMapping("/getIcCardAuth")
    @PermissionCheck("icCard_getIcCardAuth")
    public SzResult getIcCardAuth(@RequestParam(value = "page", required = false) String page,
                                  @RequestParam(value = "pageSize", required = false) String pageSize,
                                  @RequestParam(value = "startTime", required = false) String startTime,
                                  @RequestParam(value = "endTime", required = false) String endTime,
                                  @RequestParam(value = "icCardNo", required = false) String icCardNo,
                                  HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return getIcCardBu.getIcCardAuth(page, pageSize, startTime, endTime, icCardNo, plantId);
    }


    //新增IC卡授权信息
    @PostMapping("/addIcCardAuth")
    @PermissionCheck("icCard_addIcCardAuth")
    public SzResult addIcCardAuth(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String cardAuthCardNo = jsonObject.getString("cardAuthCardNo");               // 卡号
        String cardAuthDriverUserId = jsonObject.getString("cardAuthDriverUserId");   // 司机ID
        String cardAuthStartTime = jsonObject.getString("cardAuthStartTime");         // 开始时间
        String cardAuthEndTime = jsonObject.getString("cardAuthEndTime");             // 结束时间
        String cardAuthCpyId = jsonObject.getString("cardAuthCpyId");                 // 公司ID
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return getIcCardBu.addIcCardAuth(cardAuthCardNo, cardAuthDriverUserId, cardAuthCpyId, cardAuthStartTime, cardAuthEndTime, token, plantId);
    }

    //删除IC卡授权信息
    @GetMapping("/deleteIcCardAuth")
    @PermissionCheck("icCard_deleteIcCardAuth")
    public SzResult deleteIcCardAuth(@RequestParam String cardAuthId, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        return getIcCardBu.deleteIcCardAuth(cardAuthId);
    }

    //修改IC卡授权信息
    @PostMapping("/updateIcCardAuth")
    @PermissionCheck("icCard_updateIcCardAuth")
    public SzResult updateIcCardAuth(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");                                       // 授权ID
        String cardAuthDriverUserId = jsonObject.getString("cardAuthDriverUserId");   // 司机ID
        String cardAuthState = jsonObject.getString("cardAuthState");                 // 授权状态（0正常，1撤销）
        String cardAuthStartTime = jsonObject.getString("cardAuthStartTime");         // 开始时间
        String cardAuthEndTime = jsonObject.getString("cardAuthEndTime");             // 结束时间
        String cardAuthCpyId = jsonObject.getString("cardAuthCpyId");                 // 公司ID
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return getIcCardBu.upDateIcCardAuth(id, cardAuthDriverUserId, cardAuthCpyId, cardAuthState, cardAuthStartTime, cardAuthEndTime, token, plantId);
    }


    //新增IC卡信息
    @PostMapping("/addIcCardInfo")
    @PermissionCheck("icCard_addIcCardInfo")
    public SzResult addIcCardInfo(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String cardInfCardNo = jsonObject.getString("cardInfCardNo");               // 卡号
        String cardInfAgent = jsonObject.getString("cardInfAgent");                 // 代扣
        String cardInfCo = jsonObject.getString("cardInfCo");                       // 收货单位     绑定c_companys表的ID
        String cardInfChiCo = jsonObject.getString("cardInfChiCo");                 // 收货子单位名称
        String cardInfCoSupply = jsonObject.getString("cardInfCoSupply");           // 供货单位     绑定c_companys表的ID
        String cardInfChiCoSupply = jsonObject.getString("cardInfChiCoSupply");     // 供货子单位名称
        String cardInfCoTran = jsonObject.getString("cardInfCoTran");               // 运输单位     绑定c_companys表的ID
        String cardInfChiCoTran = jsonObject.getString("cardInfChiCoTran");         // 运输子单位名称
        String cardInfPreferPdt = jsonObject.getString("cardInfPreferPdt");         // 绑定品种     绑定c_products_info表的ID
        String cardInfType = jsonObject.getString("cardInfType");                   // 卡片类型     附卡（绑定车号）、附卡（绑定密码）、进货卡（绑定车号）、进货卡（绑定密码）
        String cardInfModifyReason = jsonObject.getString("cardInfModifyReason");   // 修改原因,即卡片状态：发卡、挂失、解挂、注销（我认为的）
        String cardInfTruckPwd = jsonObject.getString("cardInfTruckPwd");           // 绑定车号（牌号/密码,根据卡类型CLASS分辨是牌号还是密码）
        String codeForContinue = jsonObject.getString("codeForContinue");           // 用于判断是否继续添加
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return getIcCardBu.addIcCardInfo(cardInfCardNo, cardInfAgent, cardInfCo, cardInfChiCo, cardInfCoSupply, cardInfChiCoSupply,
                cardInfCoTran, cardInfChiCoTran, cardInfPreferPdt, cardInfType, cardInfTruckPwd, codeForContinue, token, plantId);
    }


    //修改IC卡信息
    @PostMapping("/updateIcCardInfo")
    @PermissionCheck("icCard_updateIcCardInfo")
    public SzResult updateIcCardInfo(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String cardInfAgent = jsonObject.getString("cardInfAgent");
        String cardInfCardNo = jsonObject.getString("cardInfCardNo");
        String cardInfCo = jsonObject.getString("cardInfCo");
        String cardAlias = jsonObject.getString("cardAlias");
        String[] parts3 = cardInfCo.split("\\.");
        String cardInfCo1 = null;
        String cardInfChiCo = null;
// 检查是否有至少两个部分以避免数组越界错误
        if (parts3.length >= 2) {
            cardInfCo1 = parts3[0]; // 分割后的第一部分
            cardInfChiCo = parts3[1]; // 分割后的第二部分
            // 这里可以继续使用cardInfCoSupply1和cardInfChiCo进行后续操作
        } else {
            // 处理字符串不符合预期格式的情况
            SzResult.Error("cardInfCo格式不正确，无法拆分为两部分。");
        }
//        String cardInfChiCo = jsonObject.getString("cardInfChiCo");
        String cardInfCoSupply = jsonObject.getString("cardInfCoSupply");

//        拆分cardInfCoSupply的.的前后为cardInfCoSupply1和cardInfChiCo

        String cardInfCoSupply1 = null;
        String cardInfChiCoSupply = null;
// 检查是否有至少两个部分以避免数组越界错误
        if(cardInfCoSupply !=null && !cardInfCoSupply.equals("")) {
            String[] parts = cardInfCoSupply.split("\\.");
            if (parts.length >= 2) {
                cardInfCoSupply1 = parts[0]; // 分割后的第一部分
                cardInfChiCoSupply = parts[1]; // 分割后的第二部分

                // 这里可以继续使用cardInfCoSupply1和cardInfChiCo进行后续操作
            } else {
                // 处理字符串不符合预期格式的情况
                SzResult.Error("cardInfCoSupply格式不正确，无法拆分为两部分。");
            }
        }
//        String cardInfChiCoSupply = jsonObject.getString("cardInfChiCoSupply");
        String cardInfCoTran = jsonObject.getString("cardInfCoTran");
        String[] parts2 = cardInfCoTran.split("\\.");
        String cardInfCoTran1 = null;
        String cardInfChiCoTran = null;
// 检查是否有至少两个部分以避免数组越界错误
        if (parts2.length >= 2) {
            cardInfCoTran1 = parts2[0]; // 分割后的第一部分
            cardInfChiCoTran = parts2[1]; // 分割后的第二部分
            // 这里可以继续使用cardInfCoSupply1和cardInfChiCo进行后续操作
        } else {
            // 处理字符串不符合预期格式的情况
            SzResult.Error("cardInfCoTran格式不正确，无法拆分为两部分。");
        }
//        String cardInfChiCoTran = jsonObject.getString("cardInfChiCoTran");
        String cardInfPreferPdt = jsonObject.getString("cardInfPreferPdt");
        String cardInfType = jsonObject.getString("cardInfType");
        String cardInfModifyReason = jsonObject.getString("cardInfModifyReason");
        String cardInfTruckPwd = jsonObject.getString("cardInfTruckPwd");
        String token = request.getHeader("Authorization");
        String codeForContinue = jsonObject.getString("codeForContinue");
        String plantId = request.getHeader("Plant-Id");
        //查询jsonObject里面是否有值
        Boolean isNull = jsonObject.isEmpty();
        return getIcCardBu.updateIcCardInfo(id,cardAlias, cardInfAgent, cardInfCardNo, cardInfCo1, cardInfChiCo, cardInfCoSupply1, cardInfChiCoSupply, cardInfCoTran1, cardInfChiCoTran, cardInfPreferPdt,
                cardInfType, cardInfModifyReason, cardInfTruckPwd, token, codeForContinue, isNull, plantId);
    }

    //删除IC卡信息
    @GetMapping("/deleteIcCardInfo")
    @PermissionCheck("icCard_deleteIcCardInfo")
    public SzResult deleteIcCardInfo(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return getIcCardBu.deleteIcCardInfo(id, token, plantId);
    }

    //    导出ic卡信息excel
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
//       String startTime, String endTime, String icCardNo, String co,
//                                                     String supplyCo, String tranCo, String truckNo, String cardType, String icCardStatus
        String startTime = "", endTime = "", icCardNo = "", co = "", supplyCo = "", tranCo = "", truckNo = "", cardType = "", icCardStatus = "";
        if (form != null) {
            if (form.get("startTime") != null) {
                startTime = form.get("startTime").toString();
            }
            if (form.get("endTime") != null) {
                endTime = form.get("endTime").toString();
            }
            if (form.get("icCardNo") != null) {
                icCardNo = form.get("icCardNo").toString();
            }
            if (form.get("co") != null) {
                co = form.get("co").toString();
            }
            if (form.get("supplyCo") != null) {
                supplyCo = form.get("supplyCo").toString();
            }
            if (form.get("tranCo") != null) {
                tranCo = form.get("tranCo").toString();
            }
            if (form.get("truckNo") != null) {
                truckNo = form.get("truckNo").toString();
            }
            if (form.get("cardType") != null) {
                cardType = form.get("cardType").toString();
            }
            if (form.get("icCardStatus") != null) {
                icCardStatus = form.get("icCardStatus").toString();
            }
        }
        Future<List<IcCardInfoExcelEn>> listFuture = getIcCardBu.exportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, startTime, endTime, icCardNo, co, supplyCo, tranCo, truckNo, cardType, icCardStatus, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<IcCardInfoExcelEn> icCardInfoExcelEns = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "IC卡信息";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), IcCardInfoExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("IC卡信息")
                .doWrite(icCardInfoExcelEns);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }


    /**
     * 导表
     */

    @PostMapping("/icCardAuthExportExcel")
    public void icCardAuthExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map<String, String> form = jsonParam.getObject("form", Map.class);

        Future<List<IcCardAuthExcelEn>> listFuture = getIcCardBu.icCardAuthExportExcel(fields, ids, filename, isHeader, mode, original, pager, form, sheetName, response, token, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<IcCardAuthExcelEn> icCardAuthExcelEns = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "ic卡授权信息";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), IcCardAuthExcelEn.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("ic卡授权信息").doWrite(icCardAuthExcelEns);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @GetMapping("/getCpyByICCardId")
    public SzResult getCpyByICCardId(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return getIcCardBu.getCpyByICCardId(id, token, plantId);
    }
}
